"""
企业微信加密服务 - 重构版本
整合了拆分后的各个模块
"""

from services.crypto_core import CryptoCore
from services.signature import SignatureVerifier
from handlers.message_parser import MessageParser
from config import WXConfig, WXUtils
import time

class WXBizMsgCrypt:
    """企业微信消息加解密服务 - 重构版本"""
    
    def __init__(self, token=None, encoding_aes_key=None, receive_id=None, config_file=None):
        """
        初始化企业微信加密服务
        
        Args:
            token: 企业微信Token
            encoding_aes_key: 企业微信EncodingAESKey
            receive_id: 接收者ID（自建应用用CorpID，企业微信客服用OpenKfId）
            config_file: 配置文件路径
        """
        # 加载配置
        self.config = WXConfig(config_file)
        
        # 如果传入了参数，则使用传入的参数，否则使用配置文件中的参数
        self.token = token or self.config.get_token()
        self.encoding_aes_key = encoding_aes_key or self.config.get_encoding_aes_key()
        self.receive_id = receive_id or self.config.get_receive_id()
        
        # 验证配置
        if not WXUtils.validate_config(self.token, self.encoding_aes_key, self.receive_id):
            raise ValueError("配置参数无效，请检查Token、EncodingAESKey和ReceiveId")
        
        # 初始化各个模块
        self.crypto_core = CryptoCore(self.encoding_aes_key, self.receive_id)
        self.signature_verifier = SignatureVerifier(self.token)
        self.message_parser = MessageParser()
        
        # 调试模式
        self.debug = self.config.is_debug()

    def encrypt_message(self, text, nonce=None, timestamp=None):
        """
        加密消息
        
        Args:
            text: 要加密的文本
            nonce: 随机字符串
            timestamp: 时间戳
            
        Returns:
            str: 加密后的base64字符串
        """
        try:
            return self.crypto_core.encrypt(text, nonce, timestamp)
        except Exception as e:
            if self.debug:
                print(f"加密消息失败: {str(e)}")
            return None

    def decrypt_message(self, encrypted):
        """
        解密消息
        
        Args:
            encrypted: 加密的base64字符串
            
        Returns:
            str: 解密后的文本
        """
        try:
            return self.crypto_core.decrypt(encrypted)
        except Exception as e:
            if self.debug:
                print(f"解密消息失败: {str(e)}")
            return None

    def verify_url(self, msg_signature, timestamp, nonce, echostr):
        """
        验证URL有效性
        
        Args:
            msg_signature: 消息签名
            timestamp: 时间戳
            nonce: 随机字符串
            echostr: 加密的随机字符串
            
        Returns:
            str: 解密后的随机字符串，验证失败返回None
        """
        try:
            # 验证签名
            if not self.signature_verifier.verify_signature(msg_signature, timestamp, nonce, echostr):
                if self.debug:
                    print(f"URL验证签名失败")
                return None
                
            # 解密echostr
            decrypted = self.crypto_core.decrypt(echostr)
            return decrypted
        except Exception as e:
            if self.debug:
                print(f"URL验证失败: {str(e)}")
            return None

    def decrypt_wechat_message(self, msg_signature, timestamp, nonce, encrypted_msg):
        """
        解密企业微信消息
        
        Args:
            msg_signature: 消息签名
            timestamp: 时间戳
            nonce: 随机字符串
            encrypted_msg: 加密的消息
            
        Returns:
            str: 解密后的XML消息，验证失败返回None
        """
        try:
            # 验证签名
            if not self.signature_verifier.verify_signature(msg_signature, timestamp, nonce, encrypted_msg):
                if self.debug:
                    print(f"消息签名验证失败")
                return None
                
            # 解密消息
            decrypted_xml = self.crypto_core.decrypt(encrypted_msg)
            return decrypted_xml
        except Exception as e:
            if self.debug:
                print(f"消息解密失败: {str(e)}")
            return None

    def parse_xml_message(self, xml_content):
        """
        解析XML格式的企业微信消息
        
        Args:
            xml_content: XML格式的消息内容
            
        Returns:
            dict: 解析后的消息字典
        """
        return self.message_parser.parse_xml_message(xml_content)

    def create_reply_xml(self, to_user, from_user, content, msg_type="text"):
        """
        创建回复消息的XML
        
        Args:
            to_user: 接收者
            from_user: 发送者
            content: 消息内容
            msg_type: 消息类型
            
        Returns:
            str: XML格式的回复消息
        """
        create_time = str(int(time.time()))
        return self.message_parser.create_reply_xml(to_user, from_user, create_time, msg_type, content)

    def encrypt_reply_message(self, to_user, from_user, content, msg_type="text"):
        """
        加密回复消息
        
        Args:
            to_user: 接收者
            from_user: 发送者
            content: 消息内容
            msg_type: 消息类型
            
        Returns:
            str: 加密后的回复消息
        """
        try:
            # 创建XML
            xml_content = self.create_reply_xml(to_user, from_user, content, msg_type)
            
            # 加密XML
            encrypted = self.crypto_core.encrypt(xml_content)
            
            return encrypted
        except Exception as e:
            if self.debug:
                print(f"加密回复消息失败: {str(e)}")
            return None

    def get_signature(self, timestamp, nonce, msg_encrypt):
        """
        生成签名
        
        Args:
            timestamp: 时间戳
            nonce: 随机字符串
            msg_encrypt: 加密的消息
            
        Returns:
            str: SHA1签名
        """
        return self.signature_verifier.get_signature(timestamp, nonce, msg_encrypt)

    def generate_nonce(self, length=16):
        """
        生成随机字符串
        
        Args:
            length: 字符串长度
            
        Returns:
            str: 随机字符串
        """
        return self.signature_verifier.generate_nonce(length)

    def get_current_timestamp(self):
        """
        获取当前时间戳
        
        Returns:
            str: 当前时间戳
        """
        return self.signature_verifier.get_current_timestamp()

    def update_config(self, token=None, encoding_aes_key=None, receive_id=None):
        """
        更新配置
        
        Args:
            token: 新的Token
            encoding_aes_key: 新的EncodingAESKey
            receive_id: 新的ReceiveId
        """
        if token:
            self.token = token
            self.config.set("token", token)
            self.signature_verifier.token = token
            
        if encoding_aes_key:
            self.encoding_aes_key = encoding_aes_key
            self.config.set("encoding_aes_key", encoding_aes_key)
            self.crypto_core = CryptoCore(encoding_aes_key, self.receive_id)
            
        if receive_id:
            self.receive_id = receive_id
            self.config.set("receive_id", receive_id)
            self.crypto_core.receive_id = receive_id

    def is_debug_mode(self):
        """是否开启调试模式"""
        return self.debug

    def set_debug_mode(self, debug):
        """设置调试模式"""
        self.debug = debug
        self.config.set("debug", debug) 